package com.test.langchain4j.config;

import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * Created with IntelliJ IDEA.
 *
 * @description:
 * @author: liuziyang
 * @since: 2025/8/3 18:03
 * @modifiedBy:
 * @version: 1.0
 */
@Configuration
public class RestTemplateConfig {

  @Bean
  public RestTemplate restTemplate() {
    // 创建HTTP连接池
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(100);
    connectionManager.setDefaultMaxPerRoute(20);

    // 设置超时时间
    RequestConfig requestConfig =
        RequestConfig.custom()
            .setConnectTimeout(5000, java.util.concurrent.TimeUnit.MILLISECONDS)
            .setResponseTimeout(5000, java.util.concurrent.TimeUnit.MILLISECONDS)
            .build();

    // 创建HttpClient
    var httpClient =
        HttpClients.custom()
            .setConnectionManager(connectionManager)
            .setDefaultRequestConfig(requestConfig)
            .build();

    // 创建请求工厂
    ClientHttpRequestFactory requestFactory =
        new HttpComponentsClientHttpRequestFactory(httpClient);

    // 创建RestTemplate并返回
    return new RestTemplate(requestFactory);
  }
}
